<?php

/**
 * Autor: ELIU DIAZ 
 */
class JGridGenerator {

    public $db;
    public $table = null;
    public $fields = null;
    private $where = "";
    public $pk;
    public $colTypes;
    public $filters;
    public $query;
    public $search = true;
    public $whereParams;
    public $encryptedFields;

    public function getWhere() {
        return $this->where;
    }

    public function getTotalRows() {
        if ($this->table != null) {
            $query = "SELECT COUNT(*) AS t FROM $this->table ";
        } else {
            $sql = "select * from ($this->query) consulta ";
            $query = "SELECT COUNT(*) AS t FROM ($sql) A";
        }
        $result = $this->db->queryToArray($query);
        return $result[0]["t"];
    }

    public function getTotalPages($limit = 20) {
        $count = $this->getTotalRows();
        if ($count > 0) {
            $total_pages = ceil($count / ($limit != 0 ? $limit : 1));
        } else {
            $total_pages = 0;
        }
        return $total_pages;
    }

    /**
     * Genera todo lo relativo al paginado de grids 
     */
    public function main() {
        $response = array();
        if ($this->search) {
            $this->searchConfig();
        }

        if ($this->whereParams != null) {
            $w = "";
            foreach ($this->whereParams as $p => $n) {
                $w.=isEmpty($w) ? "" : " AND ";
                $val = getParam($p);
                $w.="$n=$val ";
            }
            $this->where = isEmpty($this->where) ? " where $w" : $w;
        }

        $page = isset($_REQUEST['page']) ? $_REQUEST['page'] : ""; // get the requested page
        $limit = isset($_REQUEST['rows']) ? $_REQUEST['rows'] : ""; // get how many rows we want to have into the grid
        $sord = isset($_REQUEST['sord']) ? $_REQUEST['sord'] : ""; // get the direction
        $fieldSord = isset($_REQUEST['sidx']) ? $_REQUEST['sidx'] : ""; // get the field order

        $total_pages = $this->getTotalPages($limit);
        if ($page > $total_pages) {
            $page = $total_pages;
        }

        $start = $limit * $page - $limit; // do not put $limit*($page - 1)
        if ($start < 0)
            $start = 0;

        if ($this->table != null) {
            $SQL = "select * from $this->table $this->where";
        } else {
            $SQL = "select * from ($this->query) cosulta  $this->where";
        }
        $SQL.=" ORDER BY " . (empty($fieldSord) ? $this->pk : $fieldSord) . " " . $sord . " LIMIT " . $start . " , " . $limit;

        $result = $this->db->query_toArray($SQL, false);
        $i = 0;
        foreach ($result as $row) {
            $response["rows"][$i]['id'] = $row[$this->pk];
            $celldata = array();
            foreach ($this->fields as $fld) {
                $celldata[] = isset($row[$fld]) ? $row[$fld] : "";
                $data = array();
                foreach ($celldata as $d) {
                    $data[] = $this->strip($d);
                }
                $celldata = $data;
            }
            $response["rows"][$i]['cell'] = $celldata;
            $i++;
        }
        $count = $this->getTotalRows();
        if ($count > 0) {
            $total_pages = ceil($count / $limit);
        } else {
            $total_pages = 0;
        }
        $response["page"] = $page;
        $response["total"] = $total_pages;
        $response["records"] = $this->getTotalRows();

        echo json_encode($response);
    }

    public function setWhere($condition) {
        $this->where = " WHERE " . $condition;
    }

    /**
     * Revisa caracteresespeciales
     * @param type $value
     * @return type 
     */
    public function strip($value) {
        if (get_magic_quotes_gpc() != 0) {
            if (is_array($value))
                if ($this->array_is_associative($value)) {
                    foreach ($value as $k => $v)
                        $tmp_val[$k] = stripslashes($v);
                    $value = $tmp_val;
                }
                else
                    for ($j = 0; $j < sizeof($value); $j++)
                        $value[$j] = stripslashes($value[$j]);
            else
                $value = stripslashes($value);
        }
        return $value;
    }

    private function array_is_associative($array) {
        if (is_array($array) && !empty($array)) {
            for ($iterator = count($array) - 1; $iterator; $iterator--) {
                if (!array_key_exists($iterator, $array)) {
                    return true;
                }
            }
            return !array_key_exists(0, $array);
        }
        return false;
    }

    /**
     * Busqueda 
     */
    public function searchConfig() {
        $this->where = "";
        if (isset($_REQUEST["_search"])) {
            $v = $this->strip($_REQUEST["_search"]);
            if ($v == "true") {
                $arr = $this->strip($_REQUEST);
                $w = "";
                foreach ($arr as $k => $v) {
                    if ($this->existsField($k)) {
                        $w.=!empty($w) ? " AND " : "";
                        if ($this->colTypes[$k] == "text") {
                            $w.=$k . " LIKE ";
                            $w.= sqlValue($v, $this->colTypes[$k], true);
                        } else {
                            $w.=$k . " = ";
                            $w.= sqlValue($v, $this->colTypes[$k]);
                        }
                    } //if
                } //for
                if (!empty($w)) {
                    $this->setWhere($w);
                }
            }//if
        }//if
    }

    /**
     * Verifica si existe un campo
     * @param type $k
     * @return boolean 
     */
    private function existsField($k) {
        foreach ($this->fields as $f) {
            if ($f == $k) {
                return true;
            }
        }
        return false;
    }

}

?>